package com.lixin.web.netty.handler;

import com.lixin.constants.ExceptionConstants;
import com.lixin.exception.*;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-08-09 03:37:58
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-08-09     张李鑫                     1.0         1.0 Version
 */
@Component
public class WebSocketExceptionMapper {

    private Map<Class<? extends Throwable>, WebSocketExceptionInfo> exceptionMap = new HashMap<>();

    public WebSocketExceptionMapper() {
        addExceptionMapping(AuthException.class, 403, ExceptionConstants.AUTH_ERROR);
        addExceptionMapping(TokenExpiredException.class, 401, ExceptionConstants.TOKEN_EXPIRED);
        addExceptionMapping(LoginFailedException.class, 403, ExceptionConstants.LOGIN_FAILED);
        addExceptionMapping(DuplicateFriendRequestException.class, 409, ExceptionConstants.DUPLICATE_FRIEND_REQUEST);
        addExceptionMapping(FriendshipNotFoundException.class, 410, ExceptionConstants.FRIENDSHIP_NOT_FOUND);
        addExceptionMapping(QRCodeExpiredException.class, 410, ExceptionConstants.QRCODE_EXPIRED);
        addExceptionMapping(ParamsException.class, 1001, ExceptionConstants.PARAMS_ERROR);
        addExceptionMapping(GroupNotFindException.class, 403, ExceptionConstants.GROUP_NOT_FIND);
        addExceptionMapping(GroupDisbandedException.class, 403, ExceptionConstants.GROUP_DISBANDED);
        addExceptionMapping(UserIsNotAdmin.class, 403, ExceptionConstants.NOT_ADMIN);
    }

    private void addExceptionMapping(Class<? extends Throwable> exceptionClass, int statusCode, String errorMessage) {
        exceptionMap.put(exceptionClass, new WebSocketExceptionInfo(statusCode, errorMessage));
    }

    public WebSocketExceptionInfo getExceptionInfo(Throwable exception) {
        return exceptionMap.get(exception.getClass());
    }

    public static class WebSocketExceptionInfo {
        private final int statusCode;
        private final String errorMessage;

        public WebSocketExceptionInfo(int statusCode, String errorMessage) {
            this.statusCode = statusCode;
            this.errorMessage = errorMessage;
        }

        public int getStatusCode() {
            return statusCode;
        }

        public String getErrorMessage() {
            return errorMessage;
        }
    }
}